package com.xiyoufang.mycli.db;

import com.alibaba.druid.DbType;
import com.alibaba.druid.util.JdbcUtils;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.xiyoufang.mycli.Config;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import picocli.CommandLine;

import java.io.File;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import java.util.concurrent.Callable;

/**
 * Created by 席有芳 on 2021/11/24.
 * 已经被配置
 *
 * @author 席有芳
 */
public abstract class Connected implements Callable<Integer> {
    /**
     * 环境变量
     */
    protected final Properties env = new Properties();

    /**
     * 帮助信息
     */
    @CommandLine.Option(names = {"-h", "--help"}, description = "帮助信息", usageHelp = true)
    protected boolean help;
    /**
     * JDBC url
     */
    @CommandLine.Option(names = {"-H", "--host"}, description = "连接符, 例如: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC", interactive = true, echo = true)
    protected String url;
    /**
     * 用户名
     */
    @CommandLine.Option(names = {"-u", "--username"}, description = "用户名, 例如: root", interactive = true, echo = true)
    protected String username;
    /**
     * 密码
     */
    @CommandLine.Option(names = {"-p", "--password"}, description = "密码", interactive = true, echo = true)
    protected String password;
    /**
     * 名称
     */
    @CommandLine.Option(names = {"-n", "--name"}, defaultValue = "", description = "配置名称: 对应一个数据库, 例如: mysql", interactive = true, echo = true)
    private String name;

    /**
     * 数据库类型
     */
    protected DbType dbType;

    @Override
    public Integer call() throws Exception {
        File envFile = new File(System.getProperty("user.home", System.getenv("HOME")), MessageFormat.format(Init.ENV, StrKit.notBlank(name) ? name + "." : ""));
        if (envFile.exists()) {
            String content = Engine.use().getTemplateByString(FileUtils.readFileToString(envFile, Config.DEFAULT_CHARSET)).renderToString(System.getenv());
            try (InputStream in = IOUtils.toInputStream(content, Config.DEFAULT_CHARSET)) {
                env.load(in);
            }
        }
        url = defaultIfNull(url, "db.url");
        username = defaultIfNull(username, "db.username");
        password = defaultIfNull(password, "db.password");
        dbType = JdbcUtils.getDbTypeRaw(url, null);
        DruidPlugin dp = new DruidPlugin(url, username, password);
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
        dp.start();
        arp.start();
        return doCall();
    }

    /**
     * 手动指的值如果为Null则使用环境变量里的值
     *
     * @param value          value
     * @param defaultValeKey defaultValeKey
     * @return value
     */
    protected String defaultIfNull(String value, String defaultValeKey) {
        return value == null ? env.getProperty(defaultValeKey) : value;
    }

    /**
     * 执行
     *
     * @return int
     */
    protected abstract Integer doCall() throws Exception;
}
